/*
 * AisleNav Android Application
 * PickStoreListActivity.java
 * project.AisleNav.StoreActivity
 * 
 * CS495
 * 
 * Team:
 * 		Kirby Green
 * 		Mark Hale
 * 		Adam Warnock
 * 
 * Time: 6:14:34 PM
 * Date: Dec 4, 2011
 * 
 */
package project.AisleNav.StoreActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import project.AisleNav.Backend.Item;
import project.AisleNav.Backend.ItemList;
import project.AisleNav.Backend.Store;
import project.AisleNav.ListActivity.PickListActivity;
import project.AisleNav.AisleNavActivity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

// TODO: Auto-generated Javadoc
/**
 * PickStoreListActivity.java Allows the user to pick a store to navigate
 * 
 * @author Kirby Green
 * @version 0.1
 */
public class PickStoreListActivity extends ListActivity {

	/**
	 * Called when the activity is first created.
	 *
	 * @param savedInstanceState the saved instance state
	 * @author Kirby Green
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Read from CSV
		uploadStores();

		// Add to ListView
		String[] names = project.AisleNav.AisleNavActivity.SharedLists
				.getFavoriteStores().getStoresStrings();
		for (int i = 0; i < names.length; ++i) {
			System.out.println(names[i]
					+ " - "
					+ project.AisleNav.AisleNavActivity.SharedLists
							.getFavoriteStores().getStore(i).getId());
		}
		System.out.println("Done loading strings");

		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, names));

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// Populate the Store
				getStoreItemList((int)id, project.AisleNav.AisleNavActivity.SharedLists
						.getFavoriteStores().getStore((int) id).getId());

				// Get a local copy of the Store
				Store temp = project.AisleNav.AisleNavActivity.SharedLists
						.getFavoriteStores().getStore((int) id);

				// Add the chosen store to the current store.
				project.AisleNav.AisleNavActivity.SharedLists
						.getCurrentStoreItems().set(temp);
				
				project.AisleNav.AisleNavActivity.caller.save();

				project.AisleNav.AisleNavActivity.SharedLists
						.getCurrentStoreItems().debugPrint();

				Intent i = new Intent(PickStoreListActivity.this,
						PickListActivity.class);
				 startActivity(i);
			}
		});

	}

	/**
	 * Opens the item list for the chosen store.
	 *
	 * @param favoritesIndex the favorites index
	 * @param storeID ID number of the store to be opened.
	 * @return the store item list
	 * @author Kirby Green
	 */
	private void getStoreItemList(int favoritesIndex, int storeID) {
		String filename = "Store" + Integer.toString(storeID) + ".csv";
		System.out.println("OPENING " + filename);

		File dir = Environment.getExternalStorageDirectory();
		System.out.println("UPLOADING ITEMS");

		try {
			File f = new File(dir, filename);
			InputStream is = new FileInputStream(f);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			String line;
			try {
				System.out.println("Starting to read...");
				while ((line = reader.readLine()) != null) {
					String[] RowData = line.split(",");
					int id = 0, x = -1, y = -1, z = -1;
					String name = "NULL";
					try {
						id = Integer.parseInt(RowData[0]);
						name = RowData[1];
						x = Integer.parseInt(RowData[2]);
						y = Integer.parseInt(RowData[3]);
						z = Integer.parseInt(RowData[4]);
					} catch (NumberFormatException e) {
						System.err.println("Wrong Format: " + e.getMessage());
						e.printStackTrace();
					}
					System.out.println("Copying...");
					project.AisleNav.AisleNavActivity.SharedLists
							.getFavoriteStores().getStore(favoritesIndex).getItems()
							.addItem(new Item(id, name, x, y, z));
					System.out.println("Copying done.");
				}
			} catch (IOException e) {
				System.err.println("STORE LIST UPLOAD FAILURE: IOException");
				e.printStackTrace();
				finish();
			}
		} catch (FileNotFoundException e) {
			System.err.println("STORE LIST UPLOAD FAILURE: File Not Found");
			e.printStackTrace();
			finish();
		}

		System.out.println("STORE LIST UPLOAD COMPLETE");
	}

	/**
	 * Upload the lists of stores from the CSV file.
	 *
	 * @author Kirby Green
	 */
	private void uploadStores() {
		project.AisleNav.AisleNavActivity.SharedLists.getFavoriteStores().getStores().clear();
		InputStream is;
		File dir = Environment.getExternalStorageDirectory();
		System.out.println("UPLOADING STORES");
		try {
			File f = new File(dir, "Store_list.csv");
			is = new FileInputStream(f);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			String line;
			try {
				while ((line = reader.readLine()) != null) {
					String[] RowData = line.split(",");
					int id = -55;
					try {
						id = Integer.parseInt(RowData[0]);
					} catch (NumberFormatException e) {
						System.err.println("Couldn't format: " + RowData[0]);
						e.printStackTrace();
					}
					String name = RowData[1];
					System.out.println("Adding " + id + "," + name);
					AisleNavActivity.SharedLists.getFavoriteStores().addStore(
							new Store(id, name, new ItemList()));
				}
			} catch (IOException e) {
				System.err.println("STORE UPLOAD FAILURE: IOException");
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			System.err.println("STORE UPLOAD FAILURE: File Not Found");
			e.printStackTrace();
		}

		System.out.println("STORE UPLOAD COMPLETE");
	}

}
